package cn.samehope.pet.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import com.jfinal.kit.PathKit;
import com.jfinal.weixin.sdk.api.AccessToken;
import com.jfinal.weixin.sdk.api.AccessTokenApi;

public class FileUtil {
	
	public static String saveImageToDisk(String disk, String filename, String mediaId){
	    InputStream inputStream = getMedia(mediaId);
	    byte[] data = new byte[1024 * 8];
	    int len = 0;
	    FileOutputStream fileOutputStream = null;
	    String path = "" ;
	    try {
	        //服务器存图路径
	    	File file = new File(PathKit.getWebRootPath() + File.separator + disk);
	    	if(!file.exists()){
	    		file.mkdirs();
	    	}
	    	path = File.separator + disk + File.separator + filename + ".jpg";
	        fileOutputStream = new FileOutputStream(PathKit.getWebRootPath() + path);
	        while ((len = inputStream.read(data)) != -1) {
	            fileOutputStream.write(data, 0, len);
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        if (inputStream != null) {
	            try {
	                inputStream.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        if (fileOutputStream != null) {
	            try {
	                fileOutputStream.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    return path;
	}
	
	/**
	 * 获取临时素材
	 */
	private static InputStream getMedia(String mediaId) {
		String url = "https://api.weixin.qq.com/cgi-bin/media/get";
//	    String json = HttpKit.get(PropKit.get("accessTokenUrl") + PropKit.get("appId"));
//	    AccessToken accessToken = new AccessToken(json);
	    
	    AccessToken accessToken = AccessTokenApi.getAccessToken();
	    String params = "access_token=" + accessToken.getAccessToken() + "&media_id=" + mediaId;
	       InputStream is = null;
	       try {
	        String urlNameString = url + "?" + params;
	           URL urlGet = new URL(urlNameString);
	           HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
	           http.setRequestMethod("GET"); // 必须是get方式请求
	           http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
	           http.setDoOutput(true);
	           http.setDoInput(true);
	           http.connect();
	           // 获取文件转化为byte流
	           is = http.getInputStream();
	       } catch (Exception e) {
	           e.printStackTrace();
	       }
	    return is;
	}
	
	public static void main(String[] args){
		String aa = "总问";
		System.out.println("总问".length() +"--" +"12a".length());
	}

}
